#!/bin/sh
#
# see: dh_installdeb(1)

set -e

package="bone101"

npm_pkg_install () {
	echo "${package}:installing:[${npm_file}]"
	if [ ! -d /usr/local/lib/node_modules/ ] ; then
		mkdir -p /usr/local/lib/node_modules/ || true
	fi
	if [ -d /usr/local/lib/node_modules/${npm_project}/ ] ; then
		rm -rf /usr/local/lib/node_modules/${npm_project}/ || true
	fi

	echo "${package}:updating:[/usr/local/lib/node_modules/${npm_project}/]"
	tar xf /var/cache/${package}/${npm_file} -C /usr/local/lib/node_modules/
}

npm_install () {
	node_bin="/usr/bin/nodejs"

	unset node_version
	node_version=$(/usr/bin/nodejs --version || true)
	echo "${package}:nodejs:[${node_version}]"

	v6="v6.14.4"
	v8="v8.12.0"

	node_async="async-2.0.0-rc.6"
	node_sensortag="sensortag-1.2.3"

	case "${node_version}" in
	v8.*)
		npm_project="async"
		npm_file="${node_async}-${v6}.tar.xz"
		npm_pkg_install
		npm_project="sensortag"
		npm_file="${node_sensortag}-${v6}.tar.xz"
		npm_pkg_install
		;;
	v6.*)
		npm_project="async"
		npm_file="${node_async}-${v6}.tar.xz"
		npm_pkg_install
		npm_project="sensortag"
		npm_file="${node_sensortag}-${v6}.tar.xz"
		npm_pkg_install
		;;
	esac
}

npm_install

if [ -f /var/cache/bone101/cloud9-examples.git.tar ] ; then
	cd /var/cache/bone101/
	tar xf cloud9-examples.git.tar
	rm -rf /var/cache/bone101/cloud9-examples.git.tar || true
fi

echo "Setting up: /var/lib/cloud9/ permissions"

mkdir -p /var/lib/cloud9/ || true
chown -R 1000:1000 /var/lib/cloud9/ || true

if [ -d /var/lib/cloud9/ ] ; then
	echo "Setting up Cloud9 examples from: https://github.com/beagleboard/cloud9-examples"
	if [ -d /var/cache/bone101/cloud9-examples.git/ ] ; then
		echo "git clone --depth=1 file:///var/cache/bone101/cloud9-examples.git /var/lib/cloud9/"
		git clone --depth=1 file:///var/cache/bone101/cloud9-examples.git /var/lib/cloud9/
	else
		echo "git clone --depth=1 https://github.com/beagleboard/cloud9-examples /var/lib/cloud9/"
		git clone --depth=1 https://github.com/beagleboard/cloud9-examples /var/lib/cloud9/
	fi

	cd /var/lib/cloud9/
	git config user.email "beagle@beagleboard.org"
	git config user.name "BeagleBoard"
	git remote set-url origin https://github.com/beagleboard/cloud9-examples || true
	git pull || true

	chown -R 1000:1000 /var/lib/cloud9/ || true
fi

rm -rf /var/cache/bone101/cloud9-examples.git/ || true

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0

